package com.mengdie.shuidi;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.mengdie.shuidi.common.ClientConfig;
import com.mengdie.shuidi.event.UpdateEvent;
import com.mengdie.shuidi.model.BaseModel;
import com.mengdie.shuidi.model.UpdateEntity;
import com.mengdie.shuidi.model.UpdateInfo;
import com.mengdie.shuidi.utils.DeviceUuidFactory;
import com.mengdie.shuidi.utils.ToastUtil;
import com.mengdie.shuidi.utils.common.AppUtils;
import com.mengdie.shuidi.utils.common.DeviceUtils;
import com.mengdie.shuidi.utils.common.MD5Util;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Response;


/**
 * Created by Bin on 2015/10/27.
 */
public class AppUpdate {

    private Context mContext;
    private UpdateInfo mUpdate;

    //提示语
    private String updateMsg = "有最新的软件包哦，亲快下载吧~";

    private boolean isShow = false;

    ProgressDialog mProgressDlg;

    /* 下载包安装路径 */
    private String saveFileName;

    private static final int ON_DOWNLOADING = 1;
    private static final int DOWNLOAD_FINISH = 2;
    private int progress;

    private boolean isForceUpdate;


    private Thread downLoadThread;
    private boolean interceptFlag = false;
    private String mApkName;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ON_DOWNLOADING:
                    mProgressDlg.setProgress(progress + 1);
                    break;
                case DOWNLOAD_FINISH:
                    install(mContext, ClientConfig.DEFAULT_SAVE_FILE_PATH, mApkName);
                    break;
                default:
                    break;
            }
        }

    };


    public AppUpdate(Context context, boolean isShow) {
        this.mContext = context;
        this.isShow = isShow;


    }

    public void checkUpdate() {
        getAppVersion();
    }


    private void getAppVersion() {
        int curVersionCode = AppUtils.getAppInfo(mContext.getApplicationContext()).getVersionCode();

        String snValue = MD5Util.md5(new DeviceUuidFactory(AppContext.getInstance()).getDeviceUuid().toString() + "zhimadailirelease");

        HashMap<String, String> map = new HashMap<>();
        map.put("type", "open");
        map.put("version", curVersionCode + "");
        map.put("platform", "android");
        map.put("oem", "");
        map.put("sn", snValue);
        map.put("info", DeviceUtils.getModel());
//        map.put("origin", AppContext.getInstance().getChannelName());
        JSONObject jsonObject = new JSONObject(map);
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHead(mContext))
                .post(AppContext.getInstance().getBaseUrl() + "client/v3_check_update")
//                .post(AppContext.getInstance().getBaseUrl() + "client/partner_check_update")
                .tag(mContext)
                .upJson(jsonObject.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        triggerEvent(0);
//                        ToastUtil.showToast("更新失败,请您稍后再试...");
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        BaseModel baseModel = gson.fromJson(s, BaseModel.class);
                        if (baseModel.getRet().equals("0")) {
                            if (baseModel.getCode().equals("1")) {

                                Type versionType = new TypeToken<BaseModel<UpdateEntity>>() {
                                }.getType();
                                BaseModel<UpdateEntity> versionInfo;
                                try {
                                    versionInfo = gson.fromJson(s, versionType);
                                    UpdateEntity updateEntity = versionInfo.getData();
//                                    mUpdate = new UpdateInfo();
//                                    mUpdate.setDownloadUrl(updateEntity.getDownloadUrl());
//                                    mUpdate.setUpdateLogo(updateEntity.getDesc());
//                                    isForceUpdate = updateEntity.isForce();
                                } catch (JsonSyntaxException e) {
                                    versionInfo = gson.fromJson(s, BaseModel.class);
                                }
                                mApkName = mContext.getResources().getString(R.string.app_name) + ".apk";
                                saveFileName = ClientConfig.DEFAULT_SAVE_FILE_PATH + mApkName;
                                showUpdateInfo();
                            } else if (baseModel.getCode().equals("3") && isShow) {
                                ToastUtil.showToast("已经是最新版本了");
                                triggerEvent(0);
                            } else {
                                triggerEvent(0);
                            }

                        } else {
                            ToastUtil.showToast("出错了");
                            triggerEvent(0);
                        }

                    }
                });

    }


    private void showUpdateInfo() {
        if (mUpdate == null) {
            return;
        }

        String updateLogo = mUpdate.getUpdateLogo().replace("|", "\n");

        final Dialog dialog = new AlertDialog.Builder(mContext).create();
        dialog.show();

        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_update, null);
        dialog.setContentView(view);

        dialog.setCancelable(false);

        TextView updateContent = (TextView) dialog.findViewById(R.id.update_content);
        updateContent.setText(updateLogo);

        View dividerView = dialog.findViewById(R.id.divider);

        TextView cancelBtn = (TextView) dialog.findViewById(R.id.cancel_text);
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                triggerEvent(0);
                dialog.dismiss();
            }
        });

        TextView confirmBtn = (TextView) dialog.findViewById(R.id.confirm_text);
        confirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDownloadDialog();
                dialog.dismiss();
            }
        });

        if (isForceUpdate) {
            cancelBtn.setVisibility(View.GONE);
            dividerView.setVisibility(View.GONE);
        }


    }


    private void showDownloadDialog() {

        mProgressDlg = new ProgressDialog(mContext);
        mProgressDlg.setCancelable(false);
        mProgressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        // 设置ProgressDialog 的进度条是否不明确 false 就是不设置为不明确
        mProgressDlg.setIndeterminate(false);
        mProgressDlg.setTitle("正在更新");
        mProgressDlg.setMessage("请稍候...");
        mProgressDlg.show();
        downloadApk();
    }


    /**
     * 下载apk
     */
    private void downloadApk() {
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();
    }

    /**
     * 通过隐式意图调用系统安装程序安装APK
     */
    public static void install(Context context, String apkPath, String apkName) {
        File file = new File(apkPath, apkName);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri =
                    FileProvider.getUriForFile(context, "com.mengdie.shuidi.fileprovider", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }


    private Runnable mdownApkRunnable = new Runnable() {
        @Override
        public void run() {
            try {

                URL url = new URL(mUpdate.getDownloadUrl());
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();

//                mProgressDlg.setMax((int) length);// 设置进度条的最大值

                File file = new File(ClientConfig.DEFAULT_SAVE_FILE_PATH);
                if (!file.exists()) {
                    file.mkdir();
                }
                String apkFile = saveFileName;
                File ApkFile = new File(apkFile);
                FileOutputStream fos = new FileOutputStream(ApkFile);

                int count = 0;
                byte buf[] = new byte[1024];

                do {
                    int numread = is.read(buf);
                    count += numread;
//                    progress = count;
                    progress = (int) (((float) count / length) * 100);
                    //更新进度
                    mHandler.sendEmptyMessage(ON_DOWNLOADING);
                    if (numread <= 0) {
                        //下载完成通知安装
                        mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                        break;
                    }
                    fos.write(buf, 0, numread);
                } while (!interceptFlag);//点击取消就停止下载.

                fos.close();
                is.close();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    };

    public void triggerEvent(int type) {
        EventBus.getDefault().post(new UpdateEvent(type));
    }

}
